<template>
	<view class="page">
		<view class="title">选择视频素材</view>
		<view class="chooseVue margin20 flex-between align-center padding-row20" @click="show = true">
			<text v-if="uploadVideoUrl && videoId" style="color: #000;">视频素材-ID{{videoId}}</text>
			<text v-else>请选择视频素材</text>
			<image src="../../static/more.png" style="width: 45rpx; height: 45rpx;"></image>
		</view>
		
		<!-- 设置声音名称 -->
		<view class="inpVue margin30">
			<view class="label">设置视频名称</view>
			<input type="text" placeholder="请设置视频名称" v-model="name"/>
		</view>
		
		<!-- 添加文案 -->
		<view class="inpVue margin30">
			<view class="label">添加文案</view>
			<view class="margin20">
				<u-subsection :list="tabs" :current="current" button-color="#18AB4E" active-color="#fff" bg-color="#F3F4F6" @change="change"></u-subsection>
			</view>
			<textarea placeholder="请输入音频文案" v-if="current===0" v-model="text"></textarea>
			
			<view class="audioVue flex align-center margin20" v-if="current===1">
				<view class="playBtn relative" @click="uploadAudioPlayFun(fileUrl)">
					<image src="" style="width: 44rpx; height: 44rpx;" class="absolute-auto" v-if="!isUploadPlay"></image>
					<image src="" style="width: 44rpx; height: 44rpx;" class="absolute-auto" v-else></image>
				</view>
				<view class="flex-1 flex-between align-center padding-row20" @click="chooseAudio()">
					<text v-if="audioProgress===0">点击添加音频</text>
					<text v-else-if="audioProgress===100" style="color: #000;">{{ fileName }}</text>
					<u-line-progress active-color="#18AB4E" inactive-color="#ccc" :percent="audioProgress" :striped="true" :striped-active="true" height="36" style="width: 450rpx;" v-else></u-line-progress>
					<image src="../../static/more.png" style="width: 40rpx; height: 40rpx;"></image>
				</view>
			</view>
				
			<view class="flex align-center" v-if="current===2">
				<textarea placeholder="请输入音频文案需求" class="flex-1" v-model="aiText"></textarea>
				<view class="aiBtn text-center" @click="aiBtnFun()">Ai生成</view>
			</view>
		</view>
		
		<!-- 选择音色 -->
		<view class="inpVue margin30" v-if="current!=1">
			<view class="flex-between align-center">
				<view class="title" style="padding: 0;">选择音色</view>
				<text style="color: #18AB4E; text-decoration: underline; " @click="$tools.route('./voice')">去训练</text>
			</view>
			<view class="chooseVue margin30 flex-between align-center padding-row20" @click="show50 = true">
				<text v-if="selectId && voiceName">{{ voiceName }}-{{ voiceSex }}</text>
				<text v-else>选择音色</text>
				<image src="../../static/more.png" style="width: 45rpx; height: 45rpx;"></image>
			</view>
		</view>
		
		<!-- 是否生成字幕 -->
		<view class="inpVue margin30">
			<view class="label">是否生成字幕</view>
			<view class="margin20">
				<u-radio-group v-model="word" active-color="#18AB4E">
					<u-radio  v-for="(item, index) in words" :key="index"  :name="item.name">{{item.name}}</u-radio>
				</u-radio-group>
			</view>
		</view>
		
		<!-- 开始生成视频按钮 -->
		<view class="inpVue margin50">
			<view class="text-center margin0" style="color: #888;">当前剩余{{ aiVideoPoints }}积分</view>
			<view class="startBtn margin20" @click="startFun()">开始生成视频</view>
			<view class="flex-center align-center margin20">
				<u-checkbox v-model="checked" active-color="#18AB4E" label-size="24">公开训练后声音，可获得100积分用于合成视频</u-checkbox>
			</view>
		</view>
		
		<!-- 选择视频素材 -->
		<u-popup v-model="show" mode="left">
			<view class="popupVue">
				<view class="flex-between align-center">
					<view class="h2">我的视频素材</view>
					<text style="color: #18AB4E; text-decoration: underline; line-height: 1;" @click="chooseVideo()" v-if="videoProgress===0">上传素材</text>
					<u-line-progress active-color="#18AB4E" :percent="videoProgress" style="width: 150rpx;" v-else></u-line-progress>
				</view>
				<!-- 无数据显示 -->
				<view class="w100 flex-column align-center padding-column20 fixed-auto" v-if="videoList.length===0">
					<image src="https://ant-aiet.oss-cn-hangzhou.aliyuncs.com/assets/empty.png" style="width: 256rpx; height: 256rpx;"></image>
					<text style="color: #81868e;">暂无视频素材</text>
				</view>
				<scroll-view scroll-y class="scrollVue">
					<view class="videoVue flex-between flex-wrap">
						<view class="videoItem" v-for="(item, index) in videoList" :key="index">
							<view class="relative" style="width: 230rpx; height: 360rpx;">
								<image :src="item.videoUrl+'?x-oss-process=video/snapshot,t_1,f_jpg,w_230,m_fast,ar_auto'" style="width: 230rpx; border-radius: 12rpx 12rpx 0 0;" mode="aspectFill"></image>
								<image src="../../static/play.png" style="width: 50rpx; height: 50rpx;z-index: 99;" class="absolute-auto" @click.stop="$tools.router('../play', item.videoUrl)"></image>
								<u-icon name="more-dot-fill" size="32" color="#fff" @click.stop="toOpration(item.id, item.url)" class="menu absolute"></u-icon>
							</view>
							<view class="botVue flex-between align-center padding-row20" :style="{background: videoId==item.id ? '#18AB4E' : ''}" @click.stop="selectVideo(item)">
								<text :style="{color: videoId==item.id ? '#fff' : '#999'}" style="font-size: 24rpx;">素材ID: {{ item.id }}</text>
								<image src="../../static/radio2.png" style="width: 32rpx; height: 32rpx;" v-if="videoId==item.id"></image>
								<image src="../../static/radio0.png" style="width: 32rpx; height: 32rpx;" v-else></image>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		
		<!-- 选择音色 -->
		<u-popup v-model="show50" mode="left">
			<view class="popupVue">
				<view class="h2">选择音色</view>
				
				<scroll-view scroll-y class="scrollVue">
					<view class="voiceVue">
						<u-subsection :list="tabList" mode="button" :current="voiceCurrent"  active-color="#18AB4E" bg-color="#f5f5f5;" @change="voiceChange"></u-subsection>
						<!-- 无数据显示 -->
						<view class="w100 flex-column align-center padding-column20 fixed-auto" v-if="voiceList.length===0">
							<image src="https://ant-aiet.oss-cn-hangzhou.aliyuncs.com/assets/empty.png" style="width: 256rpx; height: 256rpx;"></image>
							<text style="color: #81868e;">无音色选择</text>
						</view>
						<view class="item flex align-center margin20" v-for="(item, index) in voiceList" :key="index">
							<view class="playBtn relative" @click="playFun(item.url, item.id)">
								<image src="" style="width: 44rpx; height: 44rpx;" class="absolute-auto" v-if="audioId!=item.id"></image>
								<image src="" style="width: 44rpx; height: 44rpx;" class="absolute-auto" v-else></image>
							</view>
							<view class="content flex-between padding-row20 align-center" @click="selectAudio(item)">
								<text style="color: #81868e;">{{ item.name }}-{{ item.sex }}</text>
								<image src="../../static/radio1.png" style="width: 40rpx; height: 40rpx;" v-if="selectId==item.id"></image>
								<image src="../../static/radio0.png" style="width: 40rpx; height: 40rpx;" v-else></image>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		
		<!-- 删除声音 -->
		<u-modal v-model="show20" content="确认删除该视频素材" confirm-color="#18AB4E" :show-cancel-button="true" @confirm="deleteFun"></u-modal>
		
		<u-action-sheet :list="actions" v-model="show60" @click="handleClick"></u-action-sheet>
	</view>
</template>

<script>
	import baseUrl from "@/common/url.js"
	import { mapState } from "vuex"
	export default {
		data(){
			return {
				name: "",
				tabs: [{ name: "文本添加" }, { name: "音频添加" }, { name: "AI生成文案" }],
				tabList: [{ name: "我的" }, { name: "推荐" }, { name: "他人" }],
				words: [{name: "否"}, {name: "是"}],
				word: "否",
				current: 0,
				text: "",
				aiText: "",
				videoProgress: 0,
				audioProgress: 0,
				fileName: "",
				fileUrl: "",
				show: false,
				show20: false,
				show50: false,
				show60: false,
				videoList: [],
				videoId: "",
				deleteId: "",
				uploadVideoUrl: "",
				innerAudioContext: null,
				isUploadPlay: false,
				voiceList: [],
				voiceType: "我的",
				voiceCurrent: 0,
				audioId: "",
				audioContext: null, 
				soundUrl: "",
				voiceName: "",
				voiceSex: "",
				soundOriginalText: "",
				aiVideoPoints: 0,
				voiceFileUrl: "",
				checked: false,
				selectId: "",
				oprationId: "",
				oprationUrl: "",
				actions: [{text: "删除该视频"}, {text: "分享给好友"}]
			}
		},
		
		async onLoad() {
			await this.getVideoList()
			await this.getVoiceList()
			await this.getPoint()
		},
		
		computed: {
			...mapState({
				user: state=> state.user
			})
		},
		
		methods: {
			change(e) {
				this.current = e
			},
			
			toOpration(id, url){
				this.oprationId = id
				this.oprationUrl = url
				this.show60 = true
			},
			
			handleClick(e){
				console.log(e)
				switch(e){
					// 删除视频
					case 0:
						this.deleteFun()
					break;
					// 分享视频
					case 1:
						this.shareFun()
					break;
				}
			},
			
			// 分享
			shareFun(){
				let that = this
				uni.downloadFile({
				    url: that.oprationUrl, // 视频地址
				    success(res) {
						wx.shareVideoMessage({
						    videoPath: res.tempFilePath,
						});
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			
			// 开始生成视频第一步
			async startFun() {
				if (this.aiVideoPoints < 30) return this.$u.toast("积分不足，请充值")
				if (!this.name) return this.$u.toast("请设置视频名称")
				if (!this.uploadVideoUrl) return this.$u.toast("请选择视频")
				if (this.current===0 && !this.text) return this.$u.toast("请输入音频文案")
				if (this.current!=1 && !this.soundUrl) return this.$u.toast("请选择音色")
				if(this.current===1 && !this.voiceFileUrl) return this.$u.toast("请添加音频")
				uni.showLoading()
				const res = await this.$request("/shuziren/userVideo/startAudio", {
					name: this.name,
					publiced: this.checked,
					uploadVideoUrl: this.uploadVideoUrl,
					kouXing: -10,
					soundUrl: [this.soundUrl, this.voiceFileUrl, this.soundUrl][this.current],
					flagHd: 0,
					soundText: [this.text, "", this.aiText][this.current],
					soundOriginalText: this.soundOriginalText,
					type: this.current===1 ? 1 : 2,
					subtitle: this.word==="否" ? 0 : 1
				}, "POST", "application/json")
				if (res.code === 200) {
					if (res.data.points > this.aiVideoPoints) return this.$u.toast(`生成此视频需要花费${res.data.points}积分，当前积分不足`)
					// 开始生成视频第二步 扣除积分
					this.$request("/aiet-user-center/user/points/subtract", {
						userId: this.user.id,
						points: res.data.points,
						type: "AI_VIDEO",
						action: "SUBTRACT"
					}, "POST", "application/json").then(result => {
						if (result.code === 200) {
							this.getPoint()
							this.startVideoFun(res.data)
						}else{
							uni.hideLoading()
							this.$u.toast(result.msg)
						}
					})
				} else {
					uni.hideLoading()
					this.$u.toast(res.msg)
				}
			},
			
			// 开始生成视频第三步
			startVideoFun(data) {
				this.$request("/shuziren/userVideo/startVideo", data, "POST", "application/json").then(res => {
					uni.hideLoading()
					if(res.code===200) {
						this.name = ""
						this.soundUrl = ""
						this.soundOriginalText = ""
						this.voiceFileUrl = ""
						this.text = ""
						this.aiText = ""
						this.checked = false
						this.voiceName =""
						this.voiceSex = ""
						this.$u.toast("视频已开始生成")
						setTimeout(()=>{
							this.$tools.route("../mine/myVideo")
						}, 1000)
					}else{
						this.$u.toast(res.msg)
					} 
				})
			},
			
			// 获取积分
			async getPoint() {
				const res = await this.$request("/aiet-user-center/user/points/summary", {}, "GET")
				if (res.code === 200) {
					this.aiVideoPoints = res.data.aiVideoPoints
				}
			},
			
			// 使用视频素材
			selectVideo(item) {
				if (this.videoId === item.id) {
					this.videoId = ""
					this.uploadVideoUrl = ""
					return 
				}
				this.videoId = item.id
				this.uploadVideoUrl = item.videoUrl
				this.show = false
			},
			
			// 使用音色
			selectAudio(item){
				if (this.selectId === item.id) {
					this.voiceName = ""
					this.voiceSex = ""
					this.soundUrl = ""
					this.soundOriginalText = ""
					this.selectId = ""
					return
				}
				this.selectId = item.id
				this.voiceName = item.name
				this.voiceSex = item.sex
				this.soundUrl = item.url
				this.soundOriginalText = item.soundText
				this.show50 = false
			},
			
			// 删除视频素材
			async deleteFun(){
				const res = await this.$request("/shuziren/userUploadVideo", {
					id: this.deleteId
				}, "DELETE")
				if(res.code===200) {
					this.$u.toast("删除成功")
					this.getVideoList()
				}
			},
			
			// 获取上传视频列表
			async getVideoList() {
				const res = await this.$request("/shuziren/userUploadVideo", {
					pageNum: 0,
					pageSize: 30
				}, "GET")
				if (res.code === 200) {
					this.videoList = res.data.content
				}
			},
			
			// 获取音色列表
			async getVoiceList() {
				const res = await this.$request("/shuziren/soundTrain/list", {
					type: this.voiceType,
					pageNum: 0,
					pageSize: 100
				}, "GET")
				if (res.code === 200) this.voiceList = res.data.content
			},
			
			voiceChange(e) {
				this.voiceType = this.tabList[e].name
				this.getVoiceList()
			},
			
			async aiBtnFun() {
				if (!this.aiText) return this.$u.toast("请输入文案需求")
				uni.showLoading()
				const res = await this.$request("/shuziren/aichat/answer", {
					applicationId: "348f9058-8780-11ef-8828-0242ac110002",
					question: this.aiText
				})
				if (res.code === 200) {
					console.log(res)
					uni.hideLoading()
					this.aiText = res.data
				} else {
					uni.hideLoading()
					this.$u.toast(res.msg)
				}
			},
			
			// 播放列表音频
			playFun(url, id){
				if(this.audioId===id) {
					this.audioContext.pause();
					this.audioId = 0
					return
				}
				if(this.audioId && this.audioId!=id) {
					this.audioContext.destroy()
					this.audioContext = null
					this.audioId = 0
				}
				this.audioId = id
				this.audioContext = uni.createInnerAudioContext();
				this.audioContext.autoplay = true;
				this.audioContext.src = url
				this.audioContext.onPlay(() => {
				  console.log('开始播放');
				});
				this.audioContext.onEnded(()=>{
					console.log('播放结束');
					this.audioId = 0
					this.audioContext.destroy()
					this.audioContext = null
				})
			},
			
			// 播放上传音频
			uploadAudioPlayFun(url){
				if(!url) return this.$u.toast("请上传音频")
				if(this.audioId) {
					this.audioContext.destroy()
					this.audioContext = null
					this.audioId = 0
				}
				if(this.isUploadPlay) {
					this.innerAudioContext.pause();
					this.isUploadPlay = false
					return
				}
				this.isUploadPlay = true
				this.innerAudioContext = uni.createInnerAudioContext();
				this.innerAudioContext.autoplay = true;
				this.innerAudioContext.src = url
				this.innerAudioContext.onPlay(() => {
				  console.log('开始播放');
				});
				this.innerAudioContext.onEnded(()=>{
					console.log('播放结束');
					this.isUploadPlay = false
					this.innerAudioContext.destroy()
					this.innerAudioContext = null
				})
			},
			
			// 选择音频文件
			chooseAudio(){
				let that = this
				wx.chooseMessageFile({
					extension: [".wav", ".mp3", ".m4a", ".amr"],
					success (res) {
					    const tempFilePaths = res.tempFiles[0]
						console.log(tempFilePaths)
						const uploadTask = uni.uploadFile({
							url: baseUrl.url + "/aiet-file-center/file",
							filePath: tempFilePaths.path,
							name: "file",
							formData: {
								"path": "shuziren/audio"
							},
							success(uploadRes) {
								let data = JSON.parse(uploadRes.data)
								console.log(data)
								if(data.code===200) {
									that.fileName = tempFilePaths.name
									that.fileUrl = data.data.fileUrl
									console.log(that.fileName, that.fileUrl)
								}else{
									that.$u.toast(data.msg)
								}
							},
							fail(uploadError){
								console.log(uploadError)
								that.$u.toast("上传失败")
							}
						});
						console.log(uploadTask)
						uploadTask.onProgressUpdate(res=>{
							that.audioprogress = res.progress
							console.log(that.audioprogress)
						})
					}
				})
			},
			
			// 保存视频
			keepVideo(data) {
				this.$request("/shuziren/userUploadVideo/add", {
					videoUrl: data.fileUrl,
					coverUrl: data.coverUrl
				}, "POST", "application/json").then(res => {
					if (res.code === 200) {
						console.log("保存视频成功")
						this.getVideoList()
					}
				})
			},
			
			// 上传视频素材
			chooseVideo(){
				let that = this
				uni.chooseVideo({
					sourceType: ['camera', 'album'],
					compressed: false,
					success(res) {
						console.log(res)
						const tempFilePaths = res.tempFilePath
						console.log(tempFilePaths)
						const uploadTask = uni.uploadFile({
							url: baseUrl.url + "/aiet-file-center/file",
							filePath: tempFilePaths,
							name: "file",
							formData: {
								"path": "shuziren/video"
							},
							success(uploadRes) {
								let data = JSON.parse(uploadRes.data)
								console.log(data)
								if(data.code===200) {
									console.log("kkkk", data,)
									that.videoProgress = 0
									that.keepVideo(data.data)
								}else{
									that.$u.toast(data.msg)
								}
							},
							fail(uploadError){
								console.log(uploadError)
								that.$u.toast("上传失败")
							}
						});
						console.log(uploadTask)
						uploadTask.onProgressUpdate(res=>{
							console.log(res)
							that.videoProgress = res.progress
						})
					}
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	.popupVue {
		width: 550rpx;
		height: 100vh;
		padding: 30rpx;
		.h2 { 
			font-weight: 700;
			font-size: 30rpx;
			color: #000;
			line-height: 1;
		}
		.upload {
			width: 100%;
			height: 88rpx;
			border-radius: 12rpx;
			background: #18AB4E;
			text-align: center;
			line-height: 88rpx;
		}
		.scrollVue {
			width: 100%;
			height: calc(100vh - 110rpx);
			margin-top: 30rpx;
			box-sizing: border-box;
			.voiceVue {
				width: 100%;
				height: 100%;
				.item {
					width: 100%;
					height: 80rpx;
					background: #fff;
					overflow: hidden;
					border-radius: 12rpx;
					.playBtn {
						width: 80rpx;
						height: 80rpx;
						background: #EBEDED;
					}
					.content {
						flex: 1;
						height: 80rpx;
						background: #f5f5f5;
					}
				}
			}
			.videoVue {
				width: 100%;
				.videoItem {
					width: 230rpx;
					height: 430rpx;
					background: #f5f5f5;
					margin-bottom: 30rpx;
					border-radius: 12rpx;
					.menu {
						right: 25rpx;
						top: 25rpx;
					}
				}
				.botVue {
					width: 100%;
					height: 70rpx;
					font-size: 24rpx;
					border-radius: 0 0 12rpx 12rpx;
				}
			}
		}
	}
	.title {
		color: #000;
		font-weight: 600;
		font-size: 28rpx;
		padding: 30rpx 0 0 30rpx;
		line-height: 1;
	}
	.tip {
		color: #81868e;
		padding: 20rpx 30rpx 0 30rpx;
	}
	.uploadBtn {
		width: 690rpx;
		height: 88rpx;
		border-radius: 12rpx;
		line-height: 88rpx;
		text-align: center;
		color: #fff;
		background: #18AB4E;
	}
	.chooseVue {
		width: 690rpx;
		height: 80rpx;
		border: 1rpx solid #EBEDED;
		border-radius: 12rpx;
		margin-top: 15rpx;
	}
	.inpVue {
		width: 690rpx;
		.label {
			color: #000;
			font-weight: 600;
			font-size: 30rpx;
		}
		.aiBtn {
			width: 100rpx; 
			height: 52rpx; 
			line-height: 52rpx; 
			color: #fff; 
			background: #18AB4E; 
			border-radius: 12rpx; 
			font-size: 24rpx;
			margin-left: 20rpx;
		}
		.startBtn {
			width: 100%;
			height: 88rpx;
			background: #18AB4E;
			border-radius: 12rpx;
			line-height: 88rpx;
			text-align: center;
			color: #fff;
			font-size: 30rpx;
		}
		textarea {
			width: 100%;
			height: 160rpx;
			border-radius: 12rpx;
			border: 1rpx solid #EBEDED;
			font-size: 28rpx;
			padding: 20rpx;
			margin-top: 20rpx;
			box-sizing: border-box;
			color: #000;
		}
		.audioVue {
			width: 100%;
			height: 80rpx;
			border: 1rpx solid #EBEDED;
			border-radius: 12rpx;
			.playBtn {
				width: 80rpx;
				height: 80rpx;
				background: #EBEDED;
				border-radius: 12rpx 0 0 12rpx;
			}
		}
		input {
			width: 100%;
			height: 88rpx;
			border: 1rpx solid #EBEDED;
			border-radius: 12rpx;
			margin-top: 20rpx;
			padding-left: 20rpx;
			font-size: 28rpx;
			box-sizing: border-box;
			color: #000;
		}
		.startBtn {
			width: 100%;
			height: 88rpx;
			background: #18AB4E;
			border-radius: 12rpx;
			line-height: 88rpx;
			text-align: center;
			color: #fff;
		}
	}
</style>